package stock;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component
@SuppressWarnings("all")
public class StockSelectImpl implements StockSelect {
	@SuppressWarnings("unused")
	@Autowired
	private ProjectSession projectSession;

	@PersistenceContext
	private EntityManager entityManager;

	@Resource
	private JdbcTemplate jdbcTemplate;

	// 手动
	@Override
	public List<JSONObject> getSelect(int date1) {
		System.out.println("---------------开始查询--------------------");
		List<JSONObject> list = new ArrayList<JSONObject>();
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		String sql0 = "select DISTINCT(t.code) from Stock t ";
		List<String> list0 = session1.createQuery(sql0).list();
		String sql1 = " from Stock t where  t.code = ?0 ORDER BY t.date desc ";
		String sql2 = " select count(*) from Stock t where  t.code = ?0 and t.zhandifu >=5   ORDER BY t.date desc ";
		String sql3 = " select count(*) from Stock t where  t.code = ?0 and t.zhandifu <= -5  ORDER BY t.date desc ";

		String sqlName = "from Stock t where t.code = ?0 ";
		// String maxDatesql = "select max(t.date) from stock t";
		// int maxDate = (Integer) session1.createSQLQuery(maxDatesql).uniqueResult();

		for (int i = 0; i < list0.size(); i++) {

			System.out.println("--------正在计算--" + list0.get(i) + "-------------------" + i);
			String code = list0.get(i);
			List<Stock> list2 = session1.createQuery(sql1).setParameter(0, code).setFirstResult(0).setMaxResults(4)
					.list();

			Float f = 5F;

			Object zhang5 = (Object) session1.createSQLQuery(sql2).setParameter(0, code).uniqueResult();
			Object die5 = (Object) session1.createSQLQuery(sql3).setParameter(0, code).uniqueResult();

			Stock stock = (Stock) session1.createQuery(sqlName).setParameter(0, code).setFirstResult(0).setMaxResults(1)
					.list().get(0);

			boolean b = false;
			float sum = 0f;
			for (int j = 0; j < list2.size(); j++) {
				Stock sc = list2.get(j);
				sum += sc.getZhandifu();
				if (sc.getZhandifu() < 0) {
					b = true;
					break;
				}
				if (sc.getChengjiaoliang() <= 0) {
					b = true;
					break;
				}
				if (sc.getName().indexOf("ST") >= 0 || sc.getName().indexOf("退") >= 0) {
					b = true;
					break;
				}
			}
			if (b == false) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("code", code);
				jsonObject.put("sum", sum);
				jsonObject.put("zhang5", zhang5);
				jsonObject.put("die5", die5);
				jsonObject.put("stock", stock.getName());
				jsonObject.put("diqv", stock.getDiqv());
				list.add(jsonObject);
			}

			System.out.println("--------符合要求--" + list.size() + "-------------------");
		}

		session1.beginTransaction();
		System.out.println(JSONArray.fromObject(list).toString());
		StockContent sc = new StockContent();
		sc.setDate(DateTools.getCurrentDateString("yyyyMMdd") + "_4");
		sc.setContent(JSONArray.fromObject(list).toString());
		sc.setCi("4");
		session1.save(sc);
		session1.getTransaction().commit();
		session1.clear();
		session1.close();
		return list;
	}

	public static int flagA = 0;
	public static int zhang = 4;

	// 手动线程计算 2023年10月30日
	@Override
	public List<JSONObject> getSelectShoudong(int date1, int zhang) {
		flagA = 0;
		this.zhang = zhang;
		System.out.println("---------------开始查询--------------------" + zhang);
		List<JSONObject> list = new ArrayList<JSONObject>();
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		String sql0 = "select DISTINCT(t.code) from Stock t ";
		List<String> list0 = session1.createQuery(sql0).setFirstResult(0).setMaxResults(5000).list();
		int xc = 10;
		int temp = list0.size() / xc;
		Thread[] threads = new Thread[10];
		for (int i = 0; i < xc; i++) {
			Thread t = null;
			if (i == xc - 1) {
				t = new Thread(new StockRunnable(list0, i * temp, list0.size(), list));
			} else {
				t = new Thread(new StockRunnable(list0, i * temp, i * temp + temp, list));
			}
			threads[i] = t;
			t.start();
		}
		for (Thread thread : threads) {
			try {
				thread.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		session1.beginTransaction();
		StockContent sc = new StockContent();
		sc.setDate(DateTools.getCurrentDateString("yyyyMMdd") + "_" + zhang);
		sc.setContent(JSONArray.fromObject(list).toString());
		sc.setCi(zhang + "");
		session1.save(sc);
		session1.getTransaction().commit();
		session1.clear();
		session1.close();
		return list;
	}

	@Override
	public List<JSONObject> getOne(int date1, int zhang) {

		String sql = " SELECT t.code,t.name,t.zhandifu,t.date,t.diqv,t.huanshoulv,t.chengjiaoliang FROM (SELECT *,@rank:=IF(@prev_group = code, @rank + 1, 1) AS row_rank,"
				+ " @prev_group:=code FROM stock  CROSS JOIN (SELECT @rank:=0, @prev_group:='') AS vars ORDER BY code, date desc) AS t WHERE row_rank <=  "
				+ zhang;

		flagA = 0;
		this.zhang = zhang;
		System.out.println("---------------开始查询--------------------" + zhang);
		List<JSONObject> list = new ArrayList<JSONObject>();
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		String sql0 = "select DISTINCT(t.code) from Stock t ";
		List<String> list0 = session1.createQuery(sql0).setFirstResult(0).setMaxResults(5000).list();
		ResultSet resultSet = null;// session1.createSQLQuery(sql).list();
		List<Stock> list1 = new ArrayList();
		List<String> listBHG = new ArrayList<String>();
		List<String> listBHG1 = new ArrayList<String>();// 余下的符合的code

		String sqlzhang5 = "select t.code,count(*) from stock  t where t.zhandifu >=5 GROUP BY t.code  ";
		String sqldie5 = " select  t.code,count(*) from stock  t where t.zhandifu <=-5 GROUP BY t.code ";
		String paichu = "select t.code ,count(*) as ct  from stock t  GROUP BY t.code   HAVING COUNT(*) < 50 ";
		List<Object[]> listzhang = session1.createSQLQuery(sqlzhang5).list();
		List<Object[]> listdie = session1.createSQLQuery(sqldie5).list();
		List<Object[]> listpachu = session1.createSQLQuery(paichu).list();
		Map mapzhang = new HashMap<String, String>();
		Map mapdie = new HashMap<String, String>();
		Map mappaichu = new HashMap<String, String>();
		for (int i = 0; i < listzhang.size(); i++) {
			Object[] obj = listzhang.get(i);
			mapzhang.put(obj[0] + "", obj[1] + "");

		}
		for (int i = 0; i < listdie.size(); i++) {
			Object[] obj = listdie.get(i);
			mapdie.put(obj[0] + "", obj[1] + "");
		}
		for (int i = 0; i < listpachu.size(); i++) {
			Object[] obj = listpachu.get(i);
			mappaichu.put(obj[0] + "", obj[1] + "");
		}

		try {

			Statement stat = jdbcTemplate.getDataSource().getConnection().createStatement();

			resultSet = stat.executeQuery(sql);
			while (resultSet.next()) {
				String code = resultSet.getString("code");
				String name = resultSet.getString("name");
				Float zhandifu = resultSet.getFloat("zhandifu");
				int date = resultSet.getInt("date");
				String diqv = resultSet.getString("diqv");
				Float huanshoulv = resultSet.getFloat("huanshoulv");
				Long chengjiaoliang = resultSet.getLong("chengjiaoliang");
				Stock jsonObject = new Stock();
				jsonObject.setCode(code);
				jsonObject.setName(name);
				jsonObject.setZhandifu(zhandifu);
				jsonObject.setDate(date);
				jsonObject.setDiqv(diqv);
				jsonObject.setHuanshoulv(huanshoulv);
				jsonObject.setChengjiaoliang(chengjiaoliang);
				if (name.indexOf("ST") >= 0 || name.indexOf("退") >= 0) {
					continue;
				}
				list1.add(jsonObject);
				if (zhandifu < 0) {
					listBHG.add(code); // 得到不需要的计算的code
				}
			}
			resultSet.close();
			stat.cancel();
			stat.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("总长：" + list1.size());
		for (int i = list1.size() - 1; i >= 0; i--) {
			Stock json = list1.get(i);
			String code = json.getCode();
			if (listBHG.contains(code)) {
				list1.remove(i);
			}
		}
		System.out.println("去掉不符合后：" + list1.size());

		Map<String, List<Stock>> groupedStudents = new HashMap<>();

		for (Stock student : list1) {
			if (listpachu.contains(student.getCode())) {
				continue;
			}
			if (groupedStudents.containsKey(student.getCode())) {
				groupedStudents.get(student.getCode()).add(student);
			} else {
				List<Stock> listtemp = new ArrayList<Stock>();
				listtemp.add(student);
				groupedStudents.put(student.getCode(), listtemp);
			}
		}
		System.out.println("分组后：" + groupedStudents.size());
		JSONArray json = new JSONArray();
		for (String className : groupedStudents.keySet()) {
			System.out.println("Class " + className + ":");
			Float f = 0f;
			JSONObject jsonObject = new JSONObject();
			for (Stock student : groupedStudents.get(className)) {
				f += student.huanshoulv;
				jsonObject.put("code", student.getCode());
				jsonObject.put("stock", student.getName());
				jsonObject.put("diqv", student.getDiqv());
			}
			jsonObject.put("sum", f);
			jsonObject.put("date", DateTools.getCurrentDate(""));
			if (null == mapdie.get(className) || "".equals(mapdie.get(className) + "")) {
				jsonObject.put("die5", "0");
			} else {
				jsonObject.put("die5", mapdie.get(className));
			}
			if (null == mapzhang.get(className) || "".equals(mapzhang.get(className) + "")) {
				jsonObject.put("zhang5", "0");
			} else {
				jsonObject.put("zhang5", mapzhang.get(className));
			}
			json.add(jsonObject);

		}
		session1.beginTransaction();
		StockContent sc = new StockContent();
		sc.setDate(DateTools.getCurrentDateString("yyyyMMdd") + "_" + zhang);
		sc.setContent(json.toString());
		sc.setCi(zhang + "");
		session1.save(sc);
		session1.getTransaction().commit();
		session1.clear();
		session1.close();
		return list;
	}

	private void collect(Collector<Stock, ?, Map<String, Double>> groupingBy) {
		// TODO Auto-generated method stub

	}

	// 自动计算三连涨
	//@Scheduled(cron = "0 10 20 * * ?")
	public List<JSONObject> getSelect1() {
		System.out.println("---------------开始查询--------------------");
		List<JSONObject> list = new ArrayList<JSONObject>();
		getOne(20230000, 3);
		return list;
	}

	// 自动计算4连涨
	//@Scheduled(cron = "0 20 20 * * ?")
	public List<JSONObject> getSelect2() {
		System.out.println("---------------开始查询--------------------");
		List<JSONObject> list = new ArrayList<JSONObject>();
		getOne(20230000, 4);
		return list;
	}

	// 自动计算5连涨
	// @Scheduled(cron = "0 30 20 * * ?")
	public List<JSONObject> getSelect3() {
		System.out.println("---------------开始查询--------------------");
		List<JSONObject> list = new ArrayList<JSONObject>();
		getOne(20230000, 5);
		return list;
	}

	// 自动计算6连涨
	//@Scheduled(cron = "0 40 20 * * ?")
	public List<JSONObject> getSelect4() {
		System.out.println("---------------开始查询--------------------");
		List<JSONObject> list = new ArrayList<JSONObject>();
		getOne(20230000, 6);
		return list;
	}

	@Override
	public List<StockContent> getContent() {
		// TODO Auto-generated method stub
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		String sql = "from StockContent t ";
		List<StockContent> list = session1.createQuery(sql).list();
		return list;
	}

	@Override
	@Transactional
	public List<JSONObject> getSelect1(int date) {
		// TODO Auto-generated method stub
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		session1.beginTransaction();
		String sql = "from StockContent t ";
		List<StockContent> list = session1.createQuery(sql).list();
		for (int i = 0; i < list.size(); i++) {
			String date1 = list.get(i).getDate();
			date1 = date1.substring(0, 8);
			if (Integer.parseInt(date1) <= date) {
				session1.delete(list.get(i));
			}
		}
		session1.getTransaction().commit();
		session1.clear();
		session1.close();
		return null;
	}

	@Override
	public List<StockContent> addpinfen(JSONArray jsonArray) {
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		session1.beginTransaction();
		String sql = "from Stock t where t.code = ?0";
		for (int i = 0; i < jsonArray.size(); i++) {

			JSONObject jsonObject = jsonArray.getJSONObject(i);
			String note1 = jsonObject.getString("note1");
			System.out.println(note1);
			if (jsonObject.getString("note1").length() <= 0) {
				continue;
			}
			String code = jsonObject.getString("code");
			Stock stock = (Stock) session1.createQuery(sql).setParameter(0, code).setMaxResults(1).setFirstResult(0)
					.uniqueResult();

			StockCode sc = (StockCode) session1.createQuery("from StockCode t where t.code = ?0").setParameter(0, code)
					.uniqueResult();
			// sc.setPingFenContent(jsonObject.getString("pingFenContent"));
			// sc.setShizhi(jsonObject.getLong("shizhi"));
			if (sc == null) {
				sc = new StockCode();
			}
			sc.setNote1(note1);
			sc.setName(stock.getName());
			sc.setCode(code);
			sc.setDate(DateTools.getCurrentDate(""));
			session1.saveOrUpdate(sc);

		}
		// TODO Auto-generated method stub
		session1.getTransaction().commit();
		session1.clear();
		session1.close();
		return null;
	}

	@Override
	public List<StockCode> getPinfen() {
		// TODO Auto-generated method stub
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		String sql = "from StockCode t ";
		List<StockCode> list = session1.createQuery(sql).list();
		return list;
	}

	@Override
	public List<StockCode> changeZX(String code, String state) {
		// TODO Auto-generated method stub
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		session1.beginTransaction();
		String sql = "update stock_code set into1 = '" + state + "' and date= '" + DateTools.getCurrentDate("")
				+ "' where code = '" + code + "'";
		int list = session1.createSQLQuery(sql).executeUpdate();
		session1.getTransaction().commit();
		session1.clear();
		session1.close();
		return null;
	}

	@Override
	public List<StockCode> getStockNote() {
		// TODO Auto-generated method stub

		Session session1 = ContextUtil.getSessionFactory1().openSession();
		String sql = "from StockCode t order by t.date desc";
		List<StockCode> list = session1.createQuery(sql).list();
		return list;
	}

	/**
	 * 查询所有的code和地区,换手率
	 */
	@Override
	public JSONArray getStockCT5() {
		// TODO Auto-generated method stub

		LocalDate currentDate = LocalDate.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		int formattedDate = Integer.parseInt(currentDate.format(formatter));
		Session session1 = ContextUtil.getSessionFactory1().openSession();

		String sql0 = "select max(t.date) from stock t";
		String maxDate = session1.createSQLQuery(sql0).uniqueResult().toString();

		String sql = "select DISTINCT(t.code),t.diqv,t.huanshoulv from stock t where t.date = ?0 ";
		List<Object[]> list = session1.createSQLQuery(sql).setParameter(0, maxDate).list();
		JSONArray jonArray = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = list.get(i);
			JSONObject j = new JSONObject();
			j.put("code", obj[0]);
			j.put("diqv", obj[1]);
			j.put("huanshoulv", obj[2]);
			jonArray.add(j);
		}
		return jonArray;
	}

	/**
	 * 查询所有的code和地区,换手率
	 */
	@Override
	public JSONArray getStockCT6() {
		// TODO Auto-generated method stub
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		String sql = "select DISTINCT(t.code),t.diqv from stock t";
		List<Object[]> list = session1.createSQLQuery(sql).list();
		JSONArray jonArray = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			Object[] obj = list.get(i);
			JSONObject j = new JSONObject();
			j.put("code", obj[0]);
			j.put("diqv", obj[1]);
			jonArray.add(j);
		}
		return jonArray;
	}

	/**
	 * 
	 * public String code;
	 * 
	 * public String gn;
	 * 
	 * public String lt;
	 * 
	 * public String cj5; public String cj10; public String cj15;
	 * 
	 * public String cjqvxian;// 成交的曲线
	 * 
	 * public String cjsumqvxian;// 成交和曲线
	 */
	@Override
	public JSONArray getStock5GN(String code) {
		// TODO Auto-generated method stub
		String sql = "Select  t.table_id,t.code,t.gn,t.cp,t.hy,t.jlr,t.ys from stock_gai_nian t where t.code in (" + code + ")";
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<Object[]> list = session1.createSQLQuery(sql).list();
		JSONArray jsonarr = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			JSONObject json = new JSONObject();
			Object[] obj = list.get(i);
			json.put("table_id", obj[0]);
			json.put("code", obj[1]);
			json.put("gn", obj[2]);
			json.put("cp", obj[3]);
			json.put("hy", obj[4]);
			json.put("jlr", obj[5]);
			json.put("ys", obj[6]);
			// json.put("cjqvxian", obj[8] + "");
			// json.put("cjsumqvxian", obj[9] + "");
			jsonarr.add(json);
		}
		return jsonarr;
	}

	@Override
	public JSONArray getStockNote(String codeall) {
		// TODO Auto-generated method stub
		String sql = "select * from stock_code t where t.code in (" + codeall + ")";
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<Object[]> list = session1.createSQLQuery(sql).list();
		JSONArray jsonarr = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			JSONObject json = new JSONObject();
			Object[] obj = list.get(i);
			json.put("table_id", obj[0] + "");
			json.put("code", obj[1] + "");
			json.put("name", obj[2] + "");
			json.put("note1", obj[3] + "");
			json.put("into1", obj[4] + "");
			json.put("date", obj[5] + "");
			jsonarr.add(json);
		}
		return jsonarr;
	}

	/**
	 * 查询几日内换手率递增
	 */
	@Override
	public JSONArray getHsldizengDay(String hsl, String day, String jiage, String select, String bo1, String bo2) {
		// TODO Auto-generated method stub

		String sql = "SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY code ORDER BY date DESC) AS row_num FROM stock ) AS temp WHERE row_num <= ?0 ";

		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<Object[]> list = session1.createSQLQuery(sql).setParameter(0, day).list();
		JSONArray jsonarr = new JSONArray();
		for (int i = 0; i < list.size(); i++) {
			JSONObject json = new JSONObject();
			Object[] obj = list.get(i);
			json.put("table_id", obj[0] + "");
			json.put("chengjiaoliang", obj[1] + "");
			json.put("code", obj[2] + "");
			json.put("danqianjia", obj[3] + "");
			json.put("date", obj[4] + "");
			json.put("diqv", obj[5] + "");
			json.put("huanshoulv", obj[6] + "");
			json.put("name", obj[7] + "");
			json.put("zhandifu", obj[8] + "");
			json.put("note1", obj[9] + "");
			json.put("create_time", obj[10] + "");
			json.put("row_num", obj[11] + "");
			jsonarr.add(json);
		}
		List<String> list1 = session1.createSQLQuery("select DISTINCT(code) from stock t").list();
		HashMap<String, JSONArray> map = new HashMap<>();
		for (int i = 0; i < list1.size(); i++) {
			String code = list1.get(i);
			JSONArray jsontemp = new JSONArray();
			for (int j = 0; j < jsonarr.size(); j++) {
				JSONObject json = jsonarr.getJSONObject(j);
				if (code.equals(json.get("code"))) {
					jsontemp.add(json);
				}
				if (jsontemp.size() >= Integer.parseInt(day)) {
					break;
				}
			}
			map.put(code, jsontemp);
		}

		List<String> listfuhe = new ArrayList<String>();

		for (Map.Entry<String, JSONArray> entry : map.entrySet()) {
			String key = entry.getKey();
			JSONArray array = entry.getValue();
			if (array.size() < Integer.parseInt(day)) {
				continue;
			}
			int b = 0;
			float sum = 0f;
			for (int i = 0; i < array.size(); i++) {
				JSONObject json = array.getJSONObject(i); 
				try {
					Float f1 = Float.parseFloat(json.get("huanshoulv").toString());
					if (f1 < Float.parseFloat(hsl)) {
						b = 1;
					} 
				} catch (Exception e) {
					System.out.println("json" + json.getString("code") + "转换出错");
				}
			}
			if (b == 0) {
				listfuhe.add(key);
			}
		}

		String result = String.join(",", listfuhe);
		JSONArray jonArray = new JSONArray();

		if (result != null && result.length() > 0) {
			String sql2 = "select DISTINCT(t.code),t.diqv from stock t where code in (" + result + ");";
			List<Object[]> list2 = session1.createSQLQuery(sql2).list();

			for (int i = 0; i < list2.size(); i++) {
				Object[] obj = list2.get(i);
				JSONObject j = new JSONObject();
				j.put("code", obj[0]);
				j.put("diqv", obj[1]);
				jonArray.add(j);
			}
		}

		return jonArray;
	}

	// @Scheduled(cron = "0 35-59,0-50 09,10 * * *") // 每小时的每分钟执行一次，在9:50到10:40之间生效
	public void executeTask() {
		// 执行您的定时任务逻辑
		System.out.println("定时任务执行中...");

		JSONArray list = this.getStockCT5();
		List<String> lists = new ArrayList<String>();
		String all = "";
		LocalDate currentDate = LocalDate.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		String formattedDate = currentDate.format(formatter);
		DecimalFormat df = new DecimalFormat("#.##");
		Date currentDate1 = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String formattedDate1 = dateFormat.format(currentDate1);

		for (int i = 0; i < list.size(); i++) {
			JSONObject json = list.getJSONObject(i);
			String diqv = json.getString("diqv");
			String code = json.getString("code");
			if ("0".equals(diqv)) {
				code = "sh" + code;
			} else {
				code = "sz" + code;
			}
			if (i % 500 == 0 && i != 0) {
				all += code + "";
				System.out.println(all);
				lists.add(all);
				all = "";
				continue;
			}
			if (i == list.size() - 1) {
				all += code + "";
				System.out.println(all);
				lists.add(all);
				break;
			}
			all += code + ",";
		}
		JSONArray jsonall = new JSONArray();
		for (int i = 0; i < lists.size(); i++) {
			JSONArray jsona = StockContrl.getCcc(lists.get(i), 1f);
			jsonall.addAll(jsona);
		}
		System.out.println(jsonall.size());
		for (int i = 0; i < list.size(); i++) {
			JSONObject json = list.getJSONObject(i);
			String diqv = json.getString("diqv");
			String code = json.getString("code");
			if ("0".equals(diqv)) {
				code = "sh" + code;
			} else {
				code = "sz" + code;
			}
			for (int j = 0; j < jsonall.size(); j++) {

				JSONObject json1 = jsonall.getJSONObject(j);
				String code1 = json1.getString("code");
				if (code1.equals(code)) {
					float f = Float.parseFloat(json1.getString("huanshoulv"))
							/ Float.parseFloat(json.getString("huanshoulv"));
					json1.put("huanshoulv0", json.getString("huanshoulv"));
					json1.put("beisu", df.format(f));
					if (f >= 5f) {
						json1.put("state", 1);
					} else {
						json1.put("state", 0);
					}
					json1.put("date", formattedDate);
					json1.put("createTime", formattedDate1);
					break;
				}
			}
		}

		for (int i = jsonall.size() - 1; i >= 0; i--) {
			JSONObject json1 = jsonall.getJSONObject(i);
			String state = json1.getString("state");
			if ("0".equals(state)) {
				jsonall.remove(i);
			}
		}

		List<Stock9dian> userList = (List<Stock9dian>) JSONArray.toCollection(jsonall, Stock9dian.class);

		Session session1 = ContextUtil.getSessionFactory1().openSession();
		session1.getTransaction().begin();
		for (int i = 0; i < userList.size(); i++) {
			session1.save(userList.get(i));
		}
		System.out.println("完成一次轮动");
		session1.getTransaction().commit();
		session1.clear();
		session1.close();
	}

	@Override
	public JSONArray get15dayLT() {
		// TODO Auto-generated method stub
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<Stock15DaySF> list = session1.createQuery("from Stock15DaySF t").list();

		return JSONArray.fromObject(list);
	}

	public static String flag = "0";

	/**
	 * 得到分歧的的地方
	 */
	@Override
	public void getFenQidayLT(String flag) {

		// TODO Auto-generated method stub
		this.wuyongy = 0;
		this.flag = flag;
		this.youy = 0;
		System.out.println("计算两天差距达到5倍的股票，并买入分歧！");
		// TODO Auto-generated method stub
		String sql = "select * from stock_gai_nian t where t.shizhi < 450 ";
		Session session = ContextUtil.getSessionFactory1().openSession();
		List<StockGaiNian> list = session.createQuery("from StockGaiNian t where t.shizhi <= ?0 and t.shizhi>=?1 ")
				.setParameter(0, 400f).setParameter(1, 40f).list();

		int numThreads = 20;
		int chunkSize = list.size() / numThreads;

		ExecutorService executor = Executors.newFixedThreadPool(numThreads);

		for (int i = 0; i < numThreads; i++) {
			final int start = i * chunkSize;
			final int end = (i == numThreads - 1) ? list.size() : (i + 1) * chunkSize;
			executor.execute(() -> processChunk(list.subList(start, end)));
			System.out.println("开启一个线程" + i);
		}
		executor.shutdown();

	}

	public static int wuyongy = 0;
	public static int youy = 0;

	private static void processChunk(List<StockGaiNian> chunk) {

		System.out.println("开始启动");
		Session session = ContextUtil.getSessionFactory1().openSession();

		int temp = 5;

		String sql3 = "from StockFenqi t where t.code1 = ?0  and t.createTime = ?1 ";
		// 在这里对每个 chunk 进行需要的操作，比如计算用户的年龄等
		String sql2 = "select t.zhandifu from stock t where t.code = ?0 ORDER BY  t.date DESC   limit  1,1";

		// List<Float> list = session.createSQLQuery(sql2).setParameter(0,
		// stock.cdo).list();

		String sql4 = "select t.huanshoulv from stock t where t.code = ?0 ORDER BY  t.date DESC   limit 1,1 ";

		String sql5 = "select t.danqianjia from stock t where t.code = ?0  order by t.date desc  limit 0,20";

		if ("0".equals(flag)) {
			sql2 = "select t.zhandifu from stock t where t.code = ?0 ORDER BY  t.date DESC   limit  0,1";
			sql4 = "select t.huanshoulv from stock t where t.code = ?0 ORDER BY  t.date DESC   limit 0,1 ";
		} else {
			sql2 = "select t.zhandifu from stock t where t.code = ?0 ORDER BY  t.date DESC   limit  1,1";
			sql4 = "select t.huanshoulv from stock t where t.code = ?0 ORDER BY  t.date DESC   limit 1,1 ";
		}
		DecimalFormat df = new DecimalFormat("#.##");
		String codeall = "";
		for (int i = 0; i < chunk.size(); i++) {

			String temp1 = "";
			if (chunk.get(i).getCode().indexOf("6") == 0) {
				temp1 = "sh" + chunk.get(i).getCode();
			} else {
				temp1 = "sz" + chunk.get(i).getCode();
			}
			if (i == chunk.size() - 1) {
				codeall += temp1;
			} else {
				codeall += temp1 + ",";
			}
		}
		JSONArray josnar = getCcc(codeall, -1000f);
		session.beginTransaction();
		for (StockGaiNian stock : chunk) {
			System.out.println("Processing user: " + stock.code);
			Float zuori_zhandifu = (Float) session.createSQLQuery(sql2).setParameter(0, stock.code).uniqueResult(); // 涨跌幅
			Float zuori_huanshoulv = (Float) session.createSQLQuery(sql4).setParameter(0, stock.code).uniqueResult();// 换手率

			if ("002536".equals(stock.getCode())) {
				System.out.println("------");
			}

			if (zuori_zhandifu == null || zuori_huanshoulv == null || zuori_huanshoulv == 0f) {
				continue;
			}
			String code1 = "";
			boolean b = false;
			boolean b1 = false;
			Float hsl = 0f;
			Float zdf = 0f;
			Float chju = 0f;
			List<Float> newList = new ArrayList<>();
			if (stock.getCode().indexOf("6") == 0) {
				code1 = "sh" + stock.getCode();
			} else {
				code1 = "sz" + stock.getCode();
			}
			for (int i = 0; i < josnar.size(); i++) {
				if (code1.equals(josnar.getJSONObject(i).getString("code"))) {

					hsl = Float.valueOf((String) josnar.getJSONObject(i).get("huanshoulv"));

					zdf = Float.valueOf((String) josnar.getJSONObject(i).get("zhangdiefu"));

					Float priceC = Float.valueOf((String) josnar.getJSONObject(i).get("jiage"));
					newList.add(priceC); // Add the new value at the beginning

					// Add the elements from the original list after the first element

					if (hsl / zuori_huanshoulv >= 2.5) {
						chju = hsl / zuori_huanshoulv;
						System.out.println(df.format(chju));
						b = true;
					}
					if (zdf < 4) {
						b1 = true;
					}
					break;
				}
			}

			if (b) {

				List<Float> listdanqianzhi = (List<Float>) session.createSQLQuery(sql5).setParameter(0, stock.code)
						.list();
				for (Float value : listdanqianzhi) {
					newList.add(value);
				}
				Float f = calculateDistanceRatio(newList);
				System.out.println(stock.code + "==有用");
				StockServiceImpl.youy++;
				StockGaiNian sn = (StockGaiNian) session.createQuery("from StockGaiNian t where t.code = ?0")
						.setParameter(0, stock.code).uniqueResult();
				String name = (String) session
						.createSQLQuery("select DISTINCT(name) from stock t where t.code = ?0 limit 0,1")
						.setParameter(0, sn.getCode()).uniqueResult();
				StockFenqi cs15 = (StockFenqi) session.createQuery(sql3).setParameter(0, stock.code)
						.setParameter(1, DateTools.getCurrentDate("yyyyMMdd")).uniqueResult();
				if (cs15 != null) {
					cs15.setCode1(sn.getCode());
					cs15.setGn1(sn.getGn());
					cs15.setName1(name);
					cs15.setZuorihuanshoulv(zuori_huanshoulv + "");
					cs15.setZuorizhangdiefu(zuori_zhandifu + "");
					cs15.setDqhuanshoulv(hsl + "");
					cs15.setDqzhangdifu(zdf + "");
					cs15.setCreateTime(DateTools.getCurrentDate("yyyyMMdd"));
					cs15.setChaju(df.format(chju));
					cs15.setPrice1(df.format(f));
					session.update(cs15);
				} else {
					StockFenqi s15 = new StockFenqi();
					s15.setCode1(sn.getCode());
					s15.setGn1(sn.getGn());
					s15.setName1(name);
					s15.setZuorihuanshoulv(zuori_huanshoulv + "");
					s15.setZuorizhangdiefu(zuori_zhandifu + "");
					s15.setDqhuanshoulv(hsl + "");
					s15.setDqzhangdifu(zdf + "");
					s15.setChaju(df.format(chju));
					s15.setCreateTime(DateTools.getCurrentDate("yyyyMMdd"));
					s15.setPrice1(df.format(f));
					session.merge(s15);
				}

			} else {
				// System.out.println(stock.code + "==无用");
				StockServiceImpl.wuyongy++;
			}
		}
		session.getTransaction().commit();
		session.clear();
		session.close();
	}

	/**
	 * 得到当前所有的代码和状态
	 * 
	 * @param codearr
	 * @param temp
	 * @return
	 */
	public static JSONArray getCcc(String codearr, Float temp) {

		JSONArray jsonarrr = new JSONArray();
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet("http://qt.gtimg.cn/q=" + codearr);

		String[] arary = codearr.split(",");
		try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String responseData = EntityUtils.toString(entity);
				// 对返回的responseData进行处理
				String[] str = responseData.split(";");
				for (int i = 0; i < str.length; i++) {
					String[] str1 = str[i].split("~");
					if (str1.length <= 1) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("name", str1[1]);
					json.put("jiage", str1[3]);
					json.put("code", arary[i]);
					json.put("zhangdiefu", str1[32]);
					json.put("huanshoulv", str1[38]);
					if (temp == -1000f) {
						json.put("shizhi", str1[45]);

					} else {
						if (Float.parseFloat(str1[38] + "") <= temp) {
							continue;
						}
						json.put("shizhi", str1[45]);
						if (Float.parseFloat(str1[45]) <= 40f) {
							continue;
						}
					}
					jsonarrr.add(json);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return jsonarrr;
	}

	/**
	 * 距离最小值 百分比，0为最小
	 * 
	 * @param list
	 * @return
	 */
	public static float calculateDistanceRatio(List<Float> list) {
		if (list.isEmpty()) {
			return -1; // Return -1 as an indication of error or invalid input
		}

		Float min = list.get(0);
		// Find the minimum value in the entire list
		for (Float num : list) {

			if (num < min) {
				min = num;
			}
		}

		// Calculate the distance ratio between list.get(0) and the minimum value
		float distance = Math.abs(list.get(0) - min);
		if (list.get(0) == 0 || list.get(0) == null) {
			return 0;
		}
		float ratio = distance / list.get(0);

		return ratio;
	}

	/**
	 * 价格波动小
	 * 
	 * @param floatList
	 * @return
	 */
	public static boolean checkZhangdi5(List<Float> floatList) {
		if (floatList == null || floatList.size() <= 0) {
			return false;
		}
		if (floatList.get(1) <= 3.5) {
			return true;
		}

		return false;
	}

	/**
	 * 成交量超过5倍
	 * 
	 * @param floatList
	 * @return
	 */
	public static boolean checkValues5(List<Float> floatList) {
		try {
			if (floatList == null || floatList.size() <= 0) {
				return false;
			}
			if (floatList.get(0) / floatList.get(1) >= 4) {
				return true;
			}
			return false;
		} catch (Exception e) {
			System.out.println("--有错误--");
			return false;
		}

	}

	@Override
	public JSONArray getFenQidayLTList(String createTime) {
		// TODO Auto-generated method stub
		if ("".equals(createTime) || null == createTime) {
			createTime = DateTools.getCurrentDate("yyyyMMdd");
		}
		Session session = ContextUtil.getSessionFactory1().openSession();
		List<StockFenqi> list = session.createQuery("from StockFenqi t where t.createTime = ?0")
				.setParameter(0, createTime).list();
		return JSONArray.fromObject(list);
	}

	@Override
	public JSONArray getFenQidayLTSelectDIS(String flag) {
		// TODO Auto-generated method stub
		Session session = ContextUtil.getSessionFactory1().openSession();
		List<String> list = session.createSQLQuery("select DISTINCT(create_time) from stock_fenqi t").list();
		return JSONArray.fromObject(list);
	}

}
